package managedbean.Sales;

import javax.faces.event.ActionEvent;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.ejb.EJB;
import session.stateless.EmployeeSessionBeanLocal;
import javax.faces.bean.ManagedProperty;
import managedbean.UserSessionManagerBean;
import java.util.ArrayList;
import session.stateless.JobSessionBeanLocal;
import entity.Customer;
import entity.Job;
import entity.PurchaseOrder;
import entity.Quotation;
import entity.SalesOrder;
import java.sql.Timestamp;
import java.util.Calendar;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import session.stateless.LogSessionBeanLocal;
import session.stateless.SalesOrderSessionBeanLocal;

@ManagedBean(name = "jobManagerBean")
@RequestScoped
public class JobManagerBean {

    @ManagedProperty(value = "#{userSessionManagerBean}")
    private UserSessionManagerBean userSessionManagerBean;
    @EJB
    private JobSessionBeanLocal jobSessionBeanLocal;
    @EJB
    private EmployeeSessionBeanLocal employeeSessionBeanLocal;
    @EJB
    private LogSessionBeanLocal logSessionBeanLocal;
    @EJB
    private SalesOrderSessionBeanLocal salesOrderSessionBeanLocal;
    private String loadAddJob;
    private String loadUpdateJob;
    private String loadSearchJob;
    private String loadViewQuotation;
    private Long jobId;
    private String userId;
    private Long custId;
    private Quotation quotation;
    private PurchaseOrder purchaseOrder;
    private static ArrayList<Quotation> quotations;
    private Timestamp jobDate;
    private Long selectedQuotationId;
    private String description;
    private Customer customer;
    private static Job job;
    private ArrayList<Job> jobs;
    private ArrayList<Job> jobs2;
    private ArrayList<SalesOrder> salesOrders;
    private ArrayList<SalesOrder> salesOrdersWaiting;
    private SalesOrder salesOrder;
    private String type;
    private Quotation selectedQuotation;
    private Boolean renderConvert = false;
    private Boolean haveConfirm = false;

    public String getLoadAddJob() {

        try {

            refreshJob();
        } catch (Exception exception) {
            try {


                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/Web_Sales/searchCustomer.xhtml?request=addJob");
            } catch (Exception ex) {
            }
        }

        return null;
    }

    public String getLoadUpdateJob() {
        try {
            refreshJob();
        } catch (Exception exception) {
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/Web_Sales/searchJob.xhtml");
            } catch (Exception ex) {
            }
        }

        return null;
    }

    public String getLoadSearchJob() {
        jobs = jobSessionBeanLocal.getJobs(userSessionManagerBean.getUserId(), true); //jobs not sent for credit check yet

        salesOrders = salesOrderSessionBeanLocal.getSalesOrders(userSessionManagerBean.getUserId(), "Pending");

        salesOrdersWaiting = new ArrayList<SalesOrder>();
        for (SalesOrder so : salesOrderSessionBeanLocal.getSalesOrders()) {
            if (so.getJob().getEmployee().getUserId().compareTo(userSessionManagerBean.getUserId()) == 0) {
                if (so.getAtpCheck().compareTo("Failed") == 0) {
                    salesOrdersWaiting.add(so);
                }
            }
        }

        salesOrders = salesOrderSessionBeanLocal.getSalesOrders(userSessionManagerBean.getUserId(), "Pending");

        if (salesOrdersWaiting.size() > 0) {
            haveConfirm = true;
        }

        return null;
    }

    // <editor-fold defaultstate="collapsed" desc="Getter & Setter methods. Click on the + sign on the left to edit the code.">
    /**
     * @return the userSessionManagerBean
     */
    public UserSessionManagerBean getUserSessionManagerBean() {
        return userSessionManagerBean;
    }

    /**
     * @param userSessionManagerBean the userSessionManagerBean to set
     */
    public void setUserSessionManagerBean(UserSessionManagerBean userSessionManagerBean) {
        this.userSessionManagerBean = userSessionManagerBean;
    }

    /**
     * @return the jobSessionLocal
     */
    public JobSessionBeanLocal getJobSessionBeanLocal() {
        return jobSessionBeanLocal;
    }

    /**
     * @param jobSessionLocal the jobSessionLocal to set
     */
    public void setJobSessionBeanLocal(JobSessionBeanLocal jobSessionBeanLocal) {
        this.jobSessionBeanLocal = jobSessionBeanLocal;
    }

    /**
     * @return the employeeSessionLocal
     */
    public EmployeeSessionBeanLocal getEmployeeSessionBeanLocal() {
        return employeeSessionBeanLocal;
    }

    /**
     * @param employeeSessionLocal the employeeSessionLocal to set
     */
    public void setEmployeeSessionBeanLocal(EmployeeSessionBeanLocal employeeSessionBeanLocal) {
        this.employeeSessionBeanLocal = employeeSessionBeanLocal;
    }

    /**
     * @param loadAddJob the loadAddJob to set
     */
    public void setLoadAddJob(String loadAddJob) {
        this.loadAddJob = loadAddJob;
    }

    /**
     * @param loadUpdateJob the loadUpdateJob to set
     */
    public void setLoadUpdateJob(String loadUpdateJob) {
        this.loadUpdateJob = loadUpdateJob;
    }

    /**
     * @param loadSearchJob the loadSearchJob to set
     */
    public void setLoadSearchJob(String loadSearchJob) {
        this.loadSearchJob = loadSearchJob;
    }

    /**
     * @return the jobId
     */
    public Long getJobId() {
        return jobId;
    }

    /**
     * @param jobId the jobId to set
     */
    public void setJobId(Long jobId) {
        this.jobId = jobId;
    }

    /**
     * @return the userId
     */
    public String getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     * @return the custId
     */
    public Long getCustId() {
        return custId;
    }

    /**
     * @param custId the custId to set
     */
    public void setCustId(Long custId) {
        this.custId = custId;
    }

    /**
     * @return the quotations
     */
    public ArrayList<Quotation> getQuotations() {
        return quotations;
    }

    /**
     * @param quotations the quotations to set
     */
    public void setQuotations(ArrayList<Quotation> quotations) {
        this.quotations = quotations;
    }

    /**
     * @return the jobDate
     */
    public Timestamp getJobDate() {
        return jobDate;
    }

    /**
     * @param jobDate the jobDate to set
     */
    public void setJobDate(Timestamp jobDate) {
        this.jobDate = jobDate;
    }

    /**
     * @return the selectedQuotationId
     */
    public Long getSelectedQuotationId() {
        return selectedQuotationId;
    }

    /**
     * @param selectedQuotationId the selectedQuotationId to set
     */
    public void setSelectedQuotationId(Long selectedQuotationId) {
        this.selectedQuotationId = selectedQuotationId;
    }

    /**
     * @return the description
     */
    public String getDescription() {
        return description;
    }

    /**
     * @param description the description to set
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * @return the quotation
     */
    public Quotation getQuotation() {
        return quotation;
    }

    /**
     * @param quotation the quotation to set
     */
    public void setQuotation(Quotation quotation) {
        this.quotation = quotation;
    }

    /**
     * @return the customer
     */
    public Customer getCustomer() {
        return customer;
    }

    /**
     * @param customer the customer to set
     */
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    /**
     * @return the jobs
     */
    public ArrayList<Job> getJobs() {
        return jobs;
    }

    /**
     * @param jobs the jobs to set
     */
    public void setJobs(ArrayList<Job> jobs) {
        this.jobs = jobs;
    }

    /**
     * @return the job
     */
    public Job getJob() {
        return job;
    }

    /**
     * @param aJob the job to set
     */
    public void setJob(Job job) {
        this.job = job;
    }

    /**
     * @return the type
     */
    public String getType() {
        return type;
    }

    /**
     * @param type the type to set
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * @return the jobs2
     */
    public ArrayList<Job> getJobs2() {
        return jobs2;
    }

    /**
     * @param jobs2 the jobs2 to set
     */
    public void setJobs2(ArrayList<Job> jobs2) {
        this.jobs2 = jobs2;
    }

    /**
     * @return the renderConvert
     */
    public Boolean getRenderConvert() {
        return renderConvert;
    }

    /**
     * @param renderConvert the renderConvert to set
     */
    public void setRenderConvert(Boolean renderConvert) {
        this.renderConvert = renderConvert;
    }

    /**
     * @return the purchaseOrder
     */
    public PurchaseOrder getPurchaseOrder() {
        return purchaseOrder;
    }

    /**
     * @param purchaseOrder the purchaseOrder to set
     */
    public void setPurchaseOrder(PurchaseOrder purchaseOrder) {
        this.purchaseOrder = purchaseOrder;
    }

    //</editor-fold>
    public void refreshJob() {
        quotations = new ArrayList<Quotation>();

        setJob((Job) userSessionManagerBean.getSelectedItem());

        userId = getJob().getEmployee().getUserId();
        customer = getJob().getCustomer();
        description = getJob().getDescription();
        jobDate = getJob().getJobDate();
        type = getJob().getType();

        if (job.getPurchaseOrder() != null) {
            purchaseOrder = job.getPurchaseOrder();
            renderConvert = true;
        }

        if (getJob().getQuotations() != null) {
            quotations = new ArrayList(getJob().getQuotations());
        }
    }

    public void addQuotation(ActionEvent event) {

        try {
            getJob().setQuotations(quotations);
            getJob().setDescription(description);
            getJob().setType(type);

            userSessionManagerBean.setSelectedItem(getJob());

            //create a new quotation
            Calendar cal = Calendar.getInstance();
            Timestamp ts = new Timestamp(cal.getTime().getTime());

            Quotation q = new Quotation();
            q.setCreationDate(ts);
            q.setStatus("Active");
            q.setRemark("New quotation created on " + cal.getTime() + ".");

            userSessionManagerBean.setSelectedQuotation(q);

            if (event.getComponent().getId().equals("btnAddForOldJob")) {
                jobSessionBeanLocal.updateJob(getJob().getJobId(), q); //expire previous quotations and add the new quotation 
                userSessionManagerBean.setSelectedJob(jobSessionBeanLocal.getJob(getJob().getJobId()));
                userSessionManagerBean.setSelectedItem(q);
            } else {
                userSessionManagerBean.setSelectedQuotation(q);
                userSessionManagerBean.setSelectedItem(job);
                userSessionManagerBean.setSelectedJob(job);
            }

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Sales/quotation.xhtml");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void addJob(ActionEvent event) {
        if (getJob().getQuotations() != null) {
            if (getJob().getQuotations().size() > 0) {
                Calendar cal = Calendar.getInstance();

                Timestamp ts = new Timestamp(cal.getTime().getTime());

                getJob().setJobDate(ts);

                if (getJob().getQuotations() != null) {
                    jobSessionBeanLocal.addJob(job.getCustomer().getId(), job.getEmployee().getUserId(), new ArrayList(job.getQuotations()), ts, null, description, type);
                } else {
                    jobSessionBeanLocal.addJob(job.getCustomer().getId(), job.getEmployee().getUserId(), null, ts, null, description, type);
                }

                try {
                    logSessionBeanLocal.addLog("Add job", "Job created for customer account: " + job.getCustomer().getId().toString(), "addJob.xhtml", userSessionManagerBean.getUserId());

                    ArrayList<String> al = new ArrayList<String>();
                    al.add("Job created");
                    al.add("You have successfully created a job. For furture quotation related to this job, please use the update job function.");
                    al.add("Click on the link to return to ");
                    al.add("continue");
                    al.add("Web_Sales/searchCustomer.xhtml?request=addJob");
                    userSessionManagerBean.setSelectedItem(al);

                    FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + getUserSessionManagerBean().getServerName() + ":"
                            + getUserSessionManagerBean().getServerPort() + "/MerlionERP-war/success.xhtml");
                } catch (Exception ex) {
                    description = ex.toString();
                }
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Quotation cannot be 0.", ""));
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Quotation cannot be 0.", ""));
        }
    }

    public void doneUpdate(ActionEvent event) {
        if (getJob().getQuotations() != null) {
            jobSessionBeanLocal.updateJob(job.getJobId(), job.getCustomer().getCustId(), job.getEmployee().getUserId(), new ArrayList(getJob().getQuotations()), job.getJobDate(), null, description, type, null);
        } else {
            jobSessionBeanLocal.updateJob(job.getJobId(), job.getCustomer().getId(), job.getEmployee().getUserId(), null, job.getJobDate(), null, description, type, null);
        }

        try {
            logSessionBeanLocal.addLog("Update job", "Job updated: " + job.getJobId(), "updateJob.xhtml", userSessionManagerBean.getUserId());

            ArrayList<String> al = new ArrayList<String>();
            al.add("Job updated");
            al.add("You have successfully updated the job. ");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("Web_Sales/searchJob.xhtml");
            userSessionManagerBean.setSelectedItem(al);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + getUserSessionManagerBean().getServerName() + ":"
                    + getUserSessionManagerBean().getServerPort() + "/MerlionERP-war/success.xhtml");
        } catch (Exception ex) {
            description = ex.toString();
        }
    }

    public void edit(ActionEvent event) {
        getUserSessionManagerBean().setSelectedItem((Job) job);
        getUserSessionManagerBean().setSelectedJob(job);

        try {
            userSessionManagerBean.setRequest("updateJob.xhtml");
            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + getUserSessionManagerBean().getServerName() + ":"
                    + getUserSessionManagerBean().getServerPort() + "/MerlionERP-war/Web_Sales/updateJob.xhtml");
        } catch (Exception ex) {
        }
    }

    public void newJob(ActionEvent event) {
        try {
            userSessionManagerBean.setRequest("addJob.xhtml");
            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + getUserSessionManagerBean().getServerName() + ":"
                    + getUserSessionManagerBean().getServerPort() + "/MerlionERP-war/Web_Sales/searchCustomer.xhtml?request=addJob");
        } catch (Exception ex) {
        }
    }

    public void onRowSelect(SelectEvent event) { //on row select of datatable
        try {
            userSessionManagerBean.setSelectedQuotation(selectedQuotation);
            userSessionManagerBean.setSelectedItem(selectedQuotation);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/Web_Sales/quotation.xhtml"); //redirect to quotation.xhtml on quotation select

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    /**
     * @return the selectedQuotation
     */
    public Quotation getSelectedQuotation() {
        return selectedQuotation;
    }

    /**
     * @param selectedQuotation the selectedQuotation to set
     */
    public void setSelectedQuotation(Quotation selectedQuotation) {
        this.selectedQuotation = selectedQuotation;
    }

    /**
     * @return the loadViewQuotation
     */
    public String getLoadViewQuotation() {
        quotations = jobSessionBeanLocal.getQuotations();
        return null;
    }

    /**
     * @param loadViewQuotation the loadViewQuotation to set
     */
    public void setLoadViewQuotation(String loadViewQuotation) {
        this.loadViewQuotation = loadViewQuotation;
    }

    public void back(ActionEvent event) {
        try {
            userSessionManagerBean.setSelectedQuotation(selectedQuotation);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/index.xhtml");

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void convertToSalesOrder(ActionEvent e) { //convert a quotation to a sales order
        try {
            userSessionManagerBean.setSelectedJob(job);

            for (Quotation q : job.getQuotations()) {
                if (q.getStatus().compareTo("Active") == 0) {
                    userSessionManagerBean.setSelectedQuotation(q);
                    userSessionManagerBean.setSelectedPurchaseOrder(job.getPurchaseOrder());
                } else {
                    FacesContext.getCurrentInstance().addMessage(null,
                            new FacesMessage(FacesMessage.SEVERITY_ERROR, "No active quotation found", ""));
                }
            }

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + getUserSessionManagerBean().getServerName() + ":"
                    + getUserSessionManagerBean().getServerPort()
                    + "/MerlionERP-war/Web_Sales/addSalesOrder.xhtml"); //redirect to purchaseOrders.xhtml
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void resolve(ActionEvent event) {
        if (salesOrdersWaiting != null) {
            userSessionManagerBean.setSelectedItem(salesOrder);

            try {
                userSessionManagerBean.setSelectedQuotation(selectedQuotation);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/Web_Sales/updateSalesOrder.xhtml"); //redirect to quotation.xhtml on quotation select

            } catch (Exception ex) {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
            }
        }
    }

    /**
     * @return the salesOrders
     */
    public ArrayList<SalesOrder> getSalesOrders() {
        return salesOrders;
    }

    /**
     * @param salesOrders the salesOrders to set
     */
    public void setSalesOrders(ArrayList<SalesOrder> salesOrders) {
        this.salesOrders = salesOrders;
    }

    /**
     * @return the salesOrdersWaiting
     */
    public ArrayList<SalesOrder> getSalesOrdersWaiting() {
        return salesOrdersWaiting;
    }

    /**
     * @param salesOrdersWaiting the salesOrdersWaiting to set
     */
    public void setSalesOrdersWaiting(ArrayList<SalesOrder> salesOrdersWaiting) {
        this.salesOrdersWaiting = salesOrdersWaiting;
    }

    /**
     * @return the salesOrder
     */
    public SalesOrder getSalesOrder() {
        return salesOrder;
    }

    /**
     * @param salesOrder the salesOrder to set
     */
    public void setSalesOrder(SalesOrder salesOrder) {
        this.salesOrder = salesOrder;
    }

    /**
     * @return the haveConfirm
     */
    public Boolean getHaveConfirm() {
        return haveConfirm;
    }

    /**
     * @param haveConfirm the haveConfirm to set
     */
    public void setHaveConfirm(Boolean haveConfirm) {
        this.haveConfirm = haveConfirm;
    }
}
